<template>
  <div class="header">
    <div class="header-left">
      <div class="logo">
        <!-- <img src="@/assets/images/home/header-logo.png" alt="" /> -->
        <img src="@/assets/images/logo.png" alt="" />
      </div>
      <!-- <div class="login-title">全流程在线归档系统</div> -->
    </div>

    <div class="header-right">
      <el-badge v-if="wdsl" is-dot :offset="[-2, 2]">
        <div class="header-msg-icon" @click="jump">
          <img src="@/assets/images/msg.png" alt="" />
        </div>
      </el-badge>
      <div v-else class="header-msg-icon" @click="jump">
        <img src="@/assets/images/msg.png" alt="" />
      </div>
      <div class="header-user-icon">
        <img src="@/assets/images/yh.png" alt="" /> {{ store.userInfo?.dwmc }}，{{
          store.userInfo?.bmmc
        }}-{{ store.userInfo?.xm }}
      </div>
      <div class="header-user-tc" @click="logout"><img src="@/assets/images/tc.png" alt="" /></div>
    </div>
    <messageDialog ref="messageDialogRef" />
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, h, onBeforeUnmount, computed } from 'vue'
import { useMainStore } from '@/store/main'
import { useXxglStore } from '@/store/xxgl'
import { ElNotification, ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router'
import messageDialog from '@/views/xxgl/dialogs/remind-message-dialog.vue'
import xxglService from '@/api/xxgl'
const store = useMainStore()
const xxStore = useXxglStore()
const lastMsg = ref()
const source = ref()
const source1 = ref()
onMounted(() => {
  if (xxStore.show) {
    getWdxxsl()
    messageDialogRef.value?.openDialog()
  }

  if (window.EventSource) {
    // 建立连接
    source.value = new EventSource(
      `${window.IPCONFIG}/api/rwgl/connectSse/ywtxxx_${
        store.userInfo.tyywid ? store.userInfo.tyywid : store.userInfo.ryid
      }-${Date.now()}`,
    )

    /**
     * 客户端收到服务器发来的数据
     */
    source.value.addEventListener('message', function (e: any) {
      if (e.data === 'HEARTBEAT') return
      const res = JSON.parse(e.data)
      lastMsg.value = res
      notifyRef.value?.close()
      xxglService.getWdxxsl().then((res) => {
        xxStore.setWdxxsl(res.data?.wdxxsl)
      })
      openWdxxNotification(res.xxlxmc, res.xxnr, false)
    })

    /**
     * 如果发生通信错误（比如连接中断），就会触发error事件
     */
    source.value.addEventListener(
      'error',
      function (e: any) {
        if (e.readyState === EventSource.CLOSED) {
          ElMessage.success('连接关闭')
        } else {
          source.value.close()
        }
      },
      false,
    )

    // 建立连接
    source1.value = new EventSource(
      `${window.IPCONFIG}/api/rwgl/connectSse/ywtxxx_${store.userInfo.ryid}`,
    )

    /**
     * 客户端收到服务器发来的数据
     */
    source1.value.addEventListener('message', function (e: any) {
      if (e.data === 'HEARTBEAT') return
      const res = JSON.parse(e.data)
      lastMsg.value = res
      notifyRef.value?.close()
      xxglService.getWdxxsl().then((res) => {
        xxStore.setWdxxsl(res.data?.wdxxsl)
      })
      openWdxxNotification(res.xxlxmc, res.xxnr, false)
    })

    /**
     * 如果发生通信错误（比如连接中断），就会触发error事件
     */
    source1.value.addEventListener(
      'error',
      function (e: any) {
        if (e.readyState === EventSource.CLOSED) {
          ElMessage.success('连接关闭')
        } else {
          source1.value.close()
        }
      },
      false,
    )
  } else {
    ElMessage.warning('你的浏览器不支持SSE')
  }
})

onBeforeUnmount(() => {
  source.value.close()
  source1.value.close()
})
/*
 * 查询未读消息数量
 */
const wdsl = computed(() => xxStore.wdxxsl)
const getWdxxsl = () => {
  xxglService.getWdxxsl().then((res) => {
    xxStore.setWdxxsl(res.data.wdxxsl)
    if (res.data.wdxxsl > 0) {
      notifyRef.value?.close()
      openWdxxNotification('消息提示', `您有 ${res.data.wdxxsl} 条未读消息，请注意查收！`, true)
    }
  })
}
const messageDialogRef = ref()
// 跳转到消息列表
const toXxgl = () => {
  router.push('/xxgl')
  notifyRef.value?.close()
}
const getIt = () => {
  notifyRef.value?.close()
  const params = { xxjlbh: lastMsg.value.messageId }
  xxglService.updateXxzt(params).then(() => {
    xxglService.getWdxxsl().then((res) => {
      xxStore.setWdxxsl(res.data.wdxxsl)
    })
  })
}
const notifyRef = ref()
// 弹出右下角消息提醒
const openWdxxNotification = (title: string, msg: string, flag: boolean) => {
  notifyRef.value = ElNotification({
    title: title,
    customClass: 'messageWindow',
    zIndex: 99999,
    message: h('p', [
      h('span', {
        class: 'WindowImg',
      }),
      h(
        'span',
        {
          class: flag ? 'WindowName' : 'MsgName',
        },
        msg,
      ),
      h(
        'span',
        {
          class: 'WindowSpanBut',
        },
        [
          h(
            'button',
            {
              onClick: flag ? toXxgl : getIt,
              class: 'el-button el-button--primary',
            },
            flag ? '去查看' : '知道了',
          ),
        ],
      ),
    ]),
    duration: 0,
    position: 'bottom-right',
  })
}

const jump = () => {
  router.push('/xxgl')
}

// 退出
const logout = () => {
  ElMessageBox.confirm('确定要退出系统吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    ElMessage.success('退出成功')
    setTimeout(() => {
      window.close()
    }, 600)
  })
}
</script>
<style lang="scss" scoped>
.header {
  position: relative;
  box-sizing: border-box;
  width: 100%;
  height: 50px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
}
.header-left {
  display: flex;
  align-items: center;
  .login-title {
    margin-left: 10px;
    margin-top: -5px;
    font-size: 16px;
    color: #1a2d45;
  }
}

.header-right {
  height: 100%;
  width: 400px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  .header-msg-icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 26px;
    height: 26px;
    background-color: #4a74a7;
    border-radius: 50%;
    cursor: pointer;
  }
  .header-user-icon {
    width: 80%;
    display: flex;
    align-items: center;
    justify-content: space-evenly;
  }

  .header-user-tc {
    cursor: pointer;
  }
}
</style>
